package backpage.service.Impl;

import backpage.dto.EmployeeLevelAdjustmentDTO;
import backpage.dto.LevelAdjustmentDTO;
import backpage.dto.LevelAdjustmentQueryDTO;
import backpage.dto.LevelAdjustmentRecordDTO;
import backpage.entity.Department;
import backpage.entity.Employee;
import backpage.entity.LevelAdjustment;
import backpage.entity.SalaryLevel;
import backpage.exception.BusinessException;
import backpage.mapper.DepartmentMapper;
import backpage.mapper.EmployeeMapper;
import backpage.mapper.LevelAdjustmentMapper;
import backpage.mapper.SalaryLevelMapper;
import backpage.service.DepartmentService;
import backpage.service.LevelAdjustmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

// LevelAdjustmentServiceImpl.java
@Service
@RequiredArgsConstructor
public class LevelAdjustmentServiceImpl implements LevelAdjustmentService {

    private final LevelAdjustmentMapper levelAdjustmentMapper;
    private final EmployeeMapper employeeMapper;
    private final DepartmentService departmentService;  // 注入 DepartmentService
    private final SalaryLevelMapper salaryLevelMapper;

    @Override
    public List<EmployeeLevelAdjustmentDTO> getAdjustableEmployees(Integer currentUserId, Integer currentUserRole, Integer departmentId) {
        // 参数校验
        if (currentUserId == null || currentUserRole == null) {
            throw new BusinessException("用户信息不完整");
        }

        // 根据角色获取可调级员工列表
        switch (currentUserRole) {
            case 1: // 部门部长
                return getEmployeesForDepartmentManager(currentUserId);
            case 2: // 总经理
                return getEmployeesForGeneralManager(departmentId);
            default:
                throw new BusinessException("无权进行调级操作");
        }
    }

    /**
     * 获取部门部长可查看的员工列表
     */
    private List<EmployeeLevelAdjustmentDTO> getEmployeesForDepartmentManager(Integer managerId) {
        Department department = departmentService.getDepartmentByManagerId(managerId);  // 使用 DepartmentService
        if (department == null) {
            throw new BusinessException("您不是任何部门的部长");
        }
        return levelAdjustmentMapper.selectAdjustableEmployees(department.getDepartmentId(), 0);
    }

    /**
     * 获取总经理可查看的员工列表
     */
    private List<EmployeeLevelAdjustmentDTO> getEmployeesForGeneralManager(Integer departmentId) {
        // 总经理可以查看所有普通员工，如果指定了部门则按部门筛选
        return levelAdjustmentMapper.selectAdjustableEmployees(departmentId, 0);
    }

    @Override
    @Transactional
    public void adjustSalaryLevel(LevelAdjustmentDTO adjustmentDTO, Integer operatorId, Integer operatorRole) throws BusinessException {
        // 验证员工是否存在
        Employee employee = employeeMapper.selectById(adjustmentDTO.getEmployeeId());
        if (employee == null) {
            throw new BusinessException("员工不存在");
        }

        // 验证权限
        validatePermission(operatorId, operatorRole, employee);

        // 验证薪资级别
        SalaryLevel newSalaryLevel = salaryLevelMapper.selectById(adjustmentDTO.getNewSalaryLevel());
        if (newSalaryLevel == null) {
            throw new BusinessException("薪资级别不存在");
        }

        // 保存调级记录
        LevelAdjustment record = new LevelAdjustment();
        record.setEmployeeId(employee.getEmployeeId());
        record.setOriginalSalaryLevel(employee.getCurrentSalaryLevel());
        record.setNewSalaryLevel(adjustmentDTO.getNewSalaryLevel());
        record.setAdjustmentDate(new Date());
        record.setOperator(operatorId);
        record.setRemark(adjustmentDTO.getRemark());
        levelAdjustmentMapper.insert(record);

        // 更新员工薪资级别
        employee.setCurrentSalaryLevel(adjustmentDTO.getNewSalaryLevel());
        employeeMapper.updateById(employee);
    }

    private void validatePermission(Integer operatorId, Integer operatorRole, Employee employee) throws BusinessException {
        // 部长只能调自己部门的普通员工
        if (operatorRole == 1) {
            Department department = departmentService.getDepartmentByManagerId(operatorId);  // 使用 DepartmentService
            if (department == null || !department.getDepartmentId().equals(employee.getDepartmentId())) {
                throw new BusinessException("无权调级该员工");
            }
            if (employee.getRole() != 0) {
                throw new BusinessException("只能调级普通员工");
            }
        }
        // 总经理不能调部长或总经理
        else if (operatorRole == 2) {
            if (employee.getRole() != 0) {
                throw new BusinessException("只能调级普通员工");
            }
        } else {
            throw new BusinessException("无权进行调级操作");
        }
    }

    @Override
    public List<LevelAdjustmentRecordDTO> getAdjustmentRecords(LevelAdjustmentQueryDTO queryDTO) {
        if (queryDTO.getStartDate() == null || queryDTO.getEndDate() == null) {
            throw new BusinessException("请选择日期范围");
        }
        return levelAdjustmentMapper.selectAdjustmentRecords(
                queryDTO.getStartDate(),
                queryDTO.getEndDate(),
                queryDTO.getEmployeeId()
        );
    }

    @Override
    public List<EmployeeLevelAdjustmentDTO> getAllEmployees() {
        List<Employee> employees = employeeMapper.selectList(null);
        if (employees == null || employees.isEmpty()) {
            return Collections.emptyList();
        }

        return employees.stream().map(employee -> {
            EmployeeLevelAdjustmentDTO dto = new EmployeeLevelAdjustmentDTO();

            dto.setEmployeeId(employee.getEmployeeId());
            dto.setEmployeeNo(employee.getEmployeeNo());
            dto.setEmployeeName(employee.getEmployeeName());
            dto.setDepartmentId(employee.getDepartmentId());
            dto.setPosition(employee.getPosition());
            dto.setCurrentSalaryLevel(employee.getCurrentSalaryLevel());
            dto.setIsActive(employee.getIsActive());
            dto.setRole(employee.getRole());

            switch (employee.getRole()) {
                case 0: dto.setRoleName("普通员工"); break;
                case 1: dto.setRoleName("部长"); break;
                case 2: dto.setRoleName("总经理"); break;
                default: dto.setRoleName("未知角色");
            }

            Department department = departmentService.queryDeptInfoById(employee.getDepartmentId());
            dto.setDepartmentName(department != null ? department.getDepartmentName() : "未分配");

            SalaryLevel salaryLevel = salaryLevelMapper.selectById(employee.getCurrentSalaryLevel());
            String levelName = salaryLevel != null ? salaryLevel.getLevelName() : "未设置";
            dto.setCurrentSalaryLevelName(levelName);
            dto.setSalaryLevelName(levelName);

            return dto;
        }).collect(Collectors.toList());
    }
}
